package com.knife.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.io.IOException;
import java.util.Collection;

public class JsonUtil {
    private JsonUtil(){}

    private static ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        objectMapper.registerModule(javaTimeModule);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * 对象序列化
     * @param t 要序列化的对象
     * @return <T>
     */
    public static <T> String objectToString(T t) {
        try {
            ObjectWriter ow = objectMapper.writer().withDefaultPrettyPrinter();
            return ow.writeValueAsString(t);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("序列化对象出错！");
        }
    }

    /**
     *  一般类解析
     * @param jsonString jsonString
     * @param t 要解析类的Class
     * @return <T>
     */
    public static <T extends Object> T stringToObject(String jsonString, Class<T> t) {

        try {
            return objectMapper.readValue(jsonString, t);
        } catch (IOException e) {
            throw new RuntimeException("反序列化对象出错！");
        }
    }

    /**
     * 集合对象反序列化 例 ：List<ObjectDTO>
     * @param jsonString jsonString
     * @param t 集合中对的Class (ObjectDTO.class)
     * @return <T> 返回的集合对象类型
     */
    public static <T extends Collection> T stringToCollection(String jsonString, Class<? extends Object> t) {

        try {
            CollectionType javaType = objectMapper.getTypeFactory().constructCollectionType(Collection.class, t);
            return objectMapper.readValue(jsonString, javaType);
        } catch (IOException e) {
            throw new RuntimeException("反序列化集合对象出错！");
        }
    }

}
//版权声明：本文为CSDN博主「feichen2016」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
//原文链接：https://blog.csdn.net/feichen2016/article/details/80028827